<template>
  <div class="refine_importship">
    <h2 class="titleblue">重点船舶</h2>
    <el-row :gutter="20" style="margin: 0;">
      <el-table :data="shipgroup" style="width: 100%" border max-height="530" v-loading="tableLoading">
        <el-table-column align="center" label="序号" width="60">
          <template slot-scope="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="船名" width=""></el-table-column>
        <el-table-column align="center" prop="mmsi" label="MMSI" width=""></el-table-column>
        <el-table-column align="center" prop="shipId" label="呼号" width=""></el-table-column>
        <el-table-column align="center" prop="longitude" label="经度" width=""></el-table-column>
        <el-table-column align="center" prop="latitude" label="纬度" width=""></el-table-column>
        <el-table-column align="center" prop="agency" label="操作" width="">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click.native.prevent="manipulate(scope.row, 'changeTo')">切换</el-button>
            <el-button size="mini" type="text" @click.native.prevent="manipulate(scope.row, 'cancel')">取消关注</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
<!--    <el-row :gutter="20">-->
<!--      <el-col :span="6" class="shipli" v-for="(item,index) in shipgroup" :key="index">-->
<!--        <div class="grid-content bg-purple" :id="'mapi'+item.id">-->
<!--          &lt;!&ndash; <img :src="item.src"> &ndash;&gt;-->
<!--          <div class="attention" @click="attention(item.id)">取消关注</div>-->
<!--          <div class="shipbtn" @click='qiehuanShip(item)'>切换</div>-->
<!--        </div>-->
<!--        <p>{{item.name}}</p>-->
<!--      </el-col>-->
<!--    </el-row>-->

    <el-dialog
      title=""
      :visible.sync="dialogDelete"
      width="30%"
      class="dialogDelete"
      append-to-body
      center>
      <span>确定要取消关注？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDelete = false">取 消</el-button>
        <el-button type="primary" @click="suredel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import * as keyShipService from '@/services/KeyShipService'
  import * as shipService from '@/services/ShipService'
  import DataTable from "@/components/common/DataTable.vue"

  export default {
    props: ['ddd'],
    components: {
      'data-table': DataTable
    },
    data: function () {
      return {
        id: '',
        deleteData: [],
        dialogDelete: false,
        length: 0,
        prevTime: 0,
        prevDraw: 0,
        prevRdraw: 0,
        hoverPg: null,
        cli: '',
        showGrids: null,
        mytiles: {},

        // 重点船舶数据
        shipgroup: [],
        shipIcons: [],
        reqNow: false,
        values: undefined,
        marks: {},
        lg: {},
        totalNum: 1,
        currentPage: 0,
        thead: [
          {name: '申报单状态', prop: 'applyStatus'},
          {name: '中文船名', prop: 'cnName'},
          {name: '英文船名', prop: 'enName'},
          {name: 'IMO编号', prop: 'imo'},
          {name: '申报日期', prop: 'createTime'},
          {name: '报给单位', prop: 'approvalUnit'}
        ],
        tableLoading: false
      };
    },
    watch: {
      ddd(oldval, newval) {
        if (oldval != newval) {
          this.getData()
        }
      }
    },
    mounted() {
      this.getData()
      setTimeout(() => {
        this.getShipNow()
      }, 1200000)
    },
    methods: {
      // 表格option操作函数
      manipulate (data, action) {
        if (action == 'cancel') {
          this.dialogDelete = true
          this.id = data.id
        } else if (action == 'changeTo') {
          this.qiehuanShip(data)
        }
      },
      getKeyShip(){
            let userId=this.$profile.id;
            return keyShipService.search(userId);
      },
      getKeyShipDetial(querystr){
        return shipService.search(querystr);
      },
      getData() {
        this.tableLoading = true
        this.getKeyShip().then(retlist => {
          let tempary=[];
            for (let k=0;k<retlist.length;k++){
                 let oneobj={};
                 oneobj.id=retlist[k].id;
                 oneobj.latitude=retlist[k].lat;
                 oneobj.longitude=retlist[k].lon;
                  oneobj.shipId=retlist[k].shipId;
                  oneobj.terminaltype="";
                  if (retlist[k].terminalType!=null && retlist[k].terminalType!="null" && retlist[k].terminalType!=""){
                    oneobj.terminaltype=retlist[k].terminalType;
                  }
                 oneobj.mmsi="";
                  if (retlist[k].mmsi!=null && retlist[k].mmsi!="null" && retlist[k].mmsi!=""){
                    oneobj.mmsi=retlist[k].mmsi;
                  }
                  oneobj.name="";
                  if (oneobj.mmsi!=null && oneobj.mmsi!="null" && oneobj.mmsi!="" && oneobj.shipId!=null && oneobj.shipId!="null" && oneobj.shipId!="" && oneobj.shipId!=undefined){
                    tempary.push(oneobj);
                  }
            }
          let querystr="";
            if (tempary.length>0){
              for (let n=0;n<tempary.length;n++){
                if (querystr==""){
                  querystr="id=in="+tempary[n].shipId;
                }else{
                  querystr=querystr+","+tempary[n].shipId;
                }
              }
            }
            if (querystr.length>0){
              this.getKeyShipDetial(querystr).then((retlist1) => {
                for (let mm=0;mm<retlist1.length;mm++){
                  for (let kk=0;kk<tempary.length;kk++){
                    if (tempary[kk].shipId==retlist1[mm].id){
                      tempary[kk].ship=retlist1[mm];
                      if (retlist1[mm].cnName!=null && retlist1[mm].cnName!="null" && retlist1[mm].cnName!=""){
                        tempary[kk].name=retlist1[mm].cnName;
                      }else if (retlist1[mm].enName!=null && retlist1[mm].enName!="null" && retlist1[mm].enName!=""){
                        tempary[kk].name=retlist1[mm].enName;
                      }else if (retlist1[mm].mmsi!=null && retlist1[mm].mmsi!="null" && retlist1[mm].mmsi!=""){
                        tempary[kk].name=retlist1[mm].mmsi;
                      }
                    }
                  }
                }
                for (let n=0;n<tempary.length;n++){
                  this.shipgroup.push(tempary[n]);
                }
                this.getLocation();
              }).then(() => {
                // this.generateShow();
              });
            }
        }).then(() => {
        });
      },
      getLocation(){
        let querymmsi="";
        for (let k = 0; k < this.shipgroup.length; k++) {
          if (this.shipgroup[k].mmsi != null && this.shipgroup[k].mmsi.trim().length > 0) {
            if (querymmsi == "") {
              querymmsi = "terminalCode.in=" + this.shipgroup[k].mmsi;
            } else {
              querymmsi = querymmsi + "," + this.shipgroup[k].mmsi;
            }
          }
        }
        shipService.findLocationAll(querymmsi).then(arylocaltion => {
          for (let m=0;m<arylocaltion.length;m++){
            for (let n=0;n<this.shipgroup.length;n++){
              if (this.shipgroup[n].mmsi==arylocaltion[m].terminalCode){
                this.shipgroup[n].latitude=arylocaltion[m].latitude;
                this.shipgroup[n].longitude=arylocaltion[m].longitude;
                break;
              }
            }
          }
          this.tableLoading = false
          // this.generateShow();
        });
      },
      getShipNow() {
        let querymmsi="";
        for (let k = 0; k < this.shipgroup.length; k++) {
          if (this.shipgroup[k].mmsi != null && this.shipgroup[k].mmsi.trim().length > 0) {
            if (querymmsi == "") {
              querymmsi = "terminalCode.in=" + this.shipgroup[k].mmsi;
            } else {
              querymmsi = querymmsi + "," + this.shipgroup[k].mmsi;
            }
          }
        }
        shipService.findLocationAll(querymmsi).then(arylocaltion => {
          for (let m=0;m<arylocaltion.length;m++){
            for (let n=0;n<this.shipgroup.length;n++){
              if (this.shipgroup[n].mmsi==arylocaltion[m].terminalCode){
                this.shipgroup[n].latitude=arylocaltion[m].latitude;
                this.shipgroup[n].longitude=arylocaltion[m].longitude;
                // console.log(this.shipgroup[n]);
                this.shipgroup[n].map.flyTo(new L.LatLng(arylocaltion[m].latitude, arylocaltion[m].longitude), 12);
                this.shipgroup[i].map.setZoom(11);
                break;
              }
            }
          }
        }).then(() => {
          setTimeout(() => {
            this.getShipNow()
          }, 1200000)
        })
      },
      reDraw(map) {
        var level = map.getZoom();
        this.cli.tileCoord.setLevel(level);
        if (level <= 10) {
          return;
        }
        var bounds = map.getBounds();
        var minx = OurNav.normalizeLon(bounds.getWest());
        var maxx = OurNav.normalizeLon(bounds.getEast());
        var miny = bounds.getSouth();
        var maxy = bounds.getNorth();

        var lt = this.cli.merc.forward(minx, maxy);
        var rb = this.cli.merc.forward(maxx, miny);

        var rcTile = new OurNav.Rect(0, 0, 0, 0);
        this.cli.tileCoord.fromMerc(lt);
        rcTile.minx = this.cli.tileCoord.col;
        rcTile.miny = this.cli.tileCoord.row;
        this.cli.tileCoord.fromMerc(rb);
        rcTile.maxx = this.cli.tileCoord.col;
        rcTile.maxy = this.cli.tileCoord.row;

        for (var x = rcTile.minx; x <= rcTile.maxx; x++) {
          for (var y = rcTile.miny; y <= rcTile.maxy; y++) {
            var key = x + "," + y + "," + level;
            var tile = this.cli.cachedTiles[key];
            if (tile) {
              OurNav.drawTile(tile, this.cli, y, x);
            }
          }
        }
        OurNav.removeWhenTooMany(this.cli);
      },
      updateData(map) {
        var level = map.getZoom();
        if (level <= 10) {
          return;
        }
        var bounds = map.getBounds();
        var minx = bounds.getWest();
        var maxx = bounds.getEast();
        var miny = bounds.getSouth();
        var maxy = bounds.getNorth();

        var to = OurNav.encodeBounds(minx, miny, maxx, maxy, this.cli, msgpack);

        if (!to) {
          return;
        }
        if (oReq) {
          oReq.abort();
          oReq = null;
        }
        var oReq = new XMLHttpRequest();
        oReq.open("POST", this.$config.SHIP_BOUNDS_URL, true);
        oReq.responseType = "arraybuffer";
        oReq.onload = (oEvent) => {
          var blob = oReq.response;
          var byteArray = new Uint8Array(blob);
          var data = msgpack.decode(byteArray);
          if (data) {
            OurNav.updateGrids(data, this.cli);
          }
          oReq = null;
        };
        if (oReq) {
          oReq.send(to);
        }

      },
      time(map) {
        if ((new Date()).getTime() - this.prevTime >= 2000) {
          this.updateData(map);
          this.prevTime = (new Date()).getTime();
        }
        if ((new Date()).getTime() - this.prevDraw >= 200) {
          this.reDraw(map);
          this.prevDraw = (new Date()).getTime();
        }
        setTimeout(() => {
          this.time(map)
        }, 30);
      },
      attention(id) {
        this.dialogDelete = true
        this.id = id
      },
      qiehuanShip(item) {
        let lat=0;
        let lon=0;
        for (let m=0;m<this.shipgroup.length;m++){
          if (this.shipgroup[m].id==item.id){
              lat=this.shipgroup[m].latitude;
              lon=this.shipgroup[m].longitude;
              break;
          }
        }
        this.qiehuan(lat,lon);
      },
      qiehuan(lat, lon) {
        var dgree = [lat, lon];
        this.$emit('qiehuan', dgree)
      },
      async suredel() {
        let retobj=await keyShipService.deleteById(this.id);
        this.dialogDelete = false;
        this.getData();
      },
      //generateShow 其实不起作用，因为后台没有返回经纬度
		generateShow(){
      // console.log(this.shipgroup);
		    for (let i = 0; i < this.shipgroup.length; i++) {
            if (this.shipgroup[i].latitude && this.shipgroup[i].longitude) {
              this.shipgroup[i].map = new L.Map('mapi' + this.shipgroup[i].id, {
                fullscreenControl: false,
                fullscreenControlOptions: {
                  position: 'topleft'
                },
                zoominfoControl: false,
                zoomControl: false,
                attributionControl: false
              });
            // var osmUrl= this.$config['outw']+'/{z}/{x}/{y}';
            //var osmUrl = this.$config['innw'] + '/{z}/{x}/{y}';
            var osmAttrib = 'Map data &copy; 国交信通 contributors';
            // console.log(this.$config.OSM_URL);
            var osm = new L.TileLayer(this.$config.OSM_URL, {minZoom: 1, maxZoom: 18, attribution: osmAttrib});

            //船位瓦片
            // var shipUrl=this.$config['outship']+'/{z}/{x}/{y}';
            //var shipUrl = this.$config['inship'] + '/{z}/{x}/{y}';
            //   console.log(this.$config.SHIP_URL);
            var shipTile = new L.TileLayer(this.$config.SHIP_URL, {minZoom: 1, maxZoom: 10});

              this.shipgroup[i].map.addLayer(osm);
              this.shipgroup[i].map.addLayer(shipTile);
              // console.log(this.shipgroup[i]);
              this.shipgroup[i].map.setView(new L.LatLng(this.shipgroup[i].latitude, this.shipgroup[i].longitude), 12);
              this.shipgroup[i].map.setZoom(11);

              //船位服务
              var tiles = new L.GridLayer({
                minZoom: 0,
                maxZoom: 18
              });

              this.cli = new OurNav.LBSClient();
              this.cli.lostTime = 30 * 24 * 3600;
              var _self = this
              tiles.createTile = function (coords) {
                var tile = L.DomUtil.create('canvas', 'leaflet-tile');
                tile.version = 0;
                var size = this.getTileSize();
                tile.width = size.x
                tile.height = size.y
                tile.col = coords.x;
                tile.row = coords.y;
                tile.level = coords.z;
                _self.cli.cachedTiles[_self.cli.getTileKey(coords)] = tile;
                return tile;
              }
              tiles.addTo(this.shipgroup[i].map)
              tiles.on("tileunload", (e) => {
                delete this.cli.cachedTiles[this.cli.getTileKey(e.coords)];
              });
              var str = {}
              str[this.shipgroup[i].terminaltype + this.shipgroup[i].mmsi] = 'red'
              this.cli.setBizShips(str);

              this.time(this.shipgroup[i].map)
              this.shipgroup[i].map.on("moveend", (e) => {
                this.prevTime = 0;
                this.prevDraw = 0;
              });

              this.shipgroup[i].map.on("zoomend", (e) => {
                this.prevTime = 0;
                this.prevDraw = 0;
                this.time(e.target)
              });

              this.shipgroup[i].map.on("movestart", (e) => {
                this.prevDraw = (new Date()).getTime();
              });

              this.shipgroup[i].map.on("zoomstart", (e) => {
                this.prevDraw = (new Date()).getTime();
                if (this.hoverPg) {
                  this.hoverPg.remove();
                  this.hoverPg = null;
                }
              });

              this.shipgroup[i].map.on("move", (e) => {
                this.prevDraw = (new Date()).getTime();
              });

              this.shipgroup[i].map.on("zoom", (e) => {
                this.prevDraw = (new Date()).getTime();
              });
              this.shipgroup[i].map.on("mousemove", (e) => {
                var pt = e.latlng;
                var lng = OurNav.normalizeLon(pt.lng);
                var lng_off = pt.lng - lng;
                var latlngs = null;
                var label = null;
                pt = this.cli.merc.forward(lng, pt.lat);
                this.cli.tileCoord.fromMerc(pt);
                var keys = Object.keys(this.cli.shipDraws);
                for (var i = keys.length - 1; i >= 0; i--) {
                  var sd = this.cli.shipDraws[keys[i]];
                  if (sd && sd.shape) {
                    if (sd.shape.contains(this.cli) && sd.shape.hitTest(this.cli, true)) {
                      latlngs = sd.shape.toLatLngs(this.cli);
                      var date = new Date(sd.last_time * 1000);
                      label = "<b><center>" + sd.getLabel() + "</center></b>";
                      label += "<hr>";
                      label += "<font color='#483D8B'>标识代码：</font>" + sd.id;
                      if (sd.length > 0 && sd.width > 0) {
                        label += "<br>" + "<font color='#483D8B'>船舶尺寸：</font>" + sd.length + " × " + sd.width;
                      }
                      var speed = sd.sog * 3600 / 1852.0;
                      speed = Math.round(speed * 100) / 100;
                      label += "<br>" + "<font color='#483D8B'>船舶速度：</font>" + speed + "节";
                      label += "<br>" + "<font color='#483D8B'>最后时间：</font>" + date.pattern("yyyy-MM-dd hh:mm:ss");
                      break;
                    }
                  }
                }

                if (this.hoverPg) {
                  this.hoverPg.remove();
                  this.hoverPg = null;
                }
                if (latlngs && lng_off != 0) {
                  for (var i = 0; i < latlngs.length; i++) {
                    latlngs[i][1] += lng_off;
                  }
                }
                if (latlngs) {
                  this.hoverPg = L.polygon(latlngs, {
                    color: 'red',
                    weight: 1.0,
                    smoothFactor: 0.5
                  });
                  if (this.hoverPg) {
                    this.hoverPg.addTo(e.target);
                    if (label) {
                      this.hoverPg.bindTooltip(label, {
                        permanent: true,
                        direction: 'right',
                        offset: [20, 0]
                      });
                    }
                  }
                }
              })
            }
          }
          this.length = this.shipgroup.length;
		}

    }
  }
</script>

<style lang='scss'>

  .refine_importship {
    box-sizing: border-box;
    overflow-x: hidden;

    .el-row {
      padding: 30px;
    }
    .grid-content {
      width: 100%;
      position: relative;
      height: 200px;
    }

    .attention {
      position: absolute;
      right: 0;
      top: 0;
      background-color: #0062cd;
      color: #fff;
      font-size: 14px;
      padding: 3px 20px;
      z-index: 1000;
      cursor: pointer;
    }
    .shipbtn {
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 1000;
      cursor: pointer;
      background-color: #0062cd;
      color: #fff;
      font-size: 14px;
      padding: 3px 8px;
    }
    .el-row p {
      font-size: 16px;
      color: #333333;
      text-align: center;
      line-height: 40px;
      margin-bottom: 10px;
    }
    .dialogDelete span {
      width: 100%;
      display: inline-block;
      text-align: center;
    }
    .border-dot .grid-content {
      height: 200px;
      border: dashed 1px #d6d6d6;
      display: block;
      text-align: center;
      line-height: 200px;
      // vertical-align: middle;
    }
    .border-dot .grid-content img {
      vertical-align: middle;
      width: auto;
      height: auto;
    }
  }

</style>
